package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: 李旭
 * @create: 2021-07-19 14:33
 **/
@RestController
@RequestMapping("/api/user/passport")
public class LoginApiController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    //提交登录
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){

        //1:判断用户名不能为空 由同学们完成
        //2:判断密码不能为空  由同学们完成
        if(null == userInfo || StringUtils.isEmpty(userInfo.getLoginName())){
            return Result.fail().message("用户名不能为空");
        }
        if(null == userInfo || StringUtils.isEmpty(userInfo.getPasswd())){
            return Result.fail().message("密码不能为空");
        }
        //3:校验帐户或密码是否正确的
        userInfo = userInfoService.login(userInfo);
        if(null != userInfo){
            //正确
            String uuid = UUID.randomUUID().toString();
            Map map = new HashMap<>();
            map.put("nickName",userInfo.getNickName());
            map.put("token", uuid);

            //保存用户信息到缓存中    K：  V： 用户的Id
            redisTemplate.opsForValue().set(uuid,userInfo.getId().toString(),7, TimeUnit.DAYS);
            return Result.ok(map);
        }else{
            return Result.fail().message("用户名或密码不正确");
        }

    }
    //收货地址
    @GetMapping("/getUserAddressList")
    public List<UserAddress> getUserAddressList(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return userInfoService.getUserAddressList(userId);
    }
}
